package edu.maplef.bookwild.schema;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import junit.framework.Assert;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalMemcacheServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;

import edu.maplef.bookwild.schema.constants.BookshipStatus;
import edu.maplef.bookwild.utils.DataCache;
import edu.maplef.bookwild.utils.PMF;

public class SechmaTest {

	private final LocalServiceTestHelper helper = new LocalServiceTestHelper(
			new LocalDatastoreServiceTestConfig());

	private final LocalServiceTestHelper helper2 = new LocalServiceTestHelper(
			new LocalMemcacheServiceTestConfig());

	@Before
	public void setUp() {
		helper.setUp();
		helper2.setUp();
	}

	@After
	public void tearDown() {
		helper.tearDown();
		helper2.tearDown();
	}

	@Test
	public void RunTest() {
		BuddyTest();
	}

	public void BuddyTest() {
		Buddy.Bookship ship = new Buddy.Bookship("1001", BookshipStatus.IDLE);
		Buddy b = new Buddy(1000, ship);
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			//存储对象
			pm.makePersistent(b);

			//获取对象
			Buddy b2 = pm.getObjectById(Buddy.class, b.getId());
			System.out.println("Hello,"
					+ b2.getId()
					+ ((Buddy.Bookship) b2.getBookships().toArray()[0])
							.getStatus());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pm.close();
		}
	}

	public void BookTest() {

		Book b = new Book();
		b.addAuthor("maple");
		b.setId("10003");
		b.setPages("1001");
		b.setTitle("maple的传说");
		b.setPublisher("清华大学出版社");

		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			//存储对象
			pm.makePersistent(b);

			//获取对象
			Book b2 = pm.getObjectById(Book.class, b.getId());
			Assert.assertEquals(false, b2 == null);
			System.out.println("Hello," + b2.getTitle());

			//缓存对象
			DataCache cache = DataCache.getInstance();
			cache.putInCache(b2.getId(), b2);
			System.out.println(cache.findInCache(b2.getId()).toString());

			//查询对象
			Query query = pm.newQuery(Book.class);
			query.setFilter("author == authorParam");
			query.setOrdering("pages desc");
			query.declareParameters("String authorParam");
			List<Book> results = (List<Book>) query.execute("maple");
			if (results.iterator().hasNext()) {
				for (Book e : results) {
					System.out.println("Hello Query, " + b2.getTitle());
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pm.close();
		}
	}
}